{% extends "templates/web.html" %}

{% block page_content %}
<link rel="stylesheet" type="text/css" href="/assets/upsystem/css/tms_common.css">
<style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }

        .shipping-calculator-page {
            min-height: 100vh;
            background-color: #f5f5f5;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 0;
            text-align: center;
        }

        .header h1 {
            font-size: 28px;
            font-weight: 600;
            margin-bottom: 8px;
        }

        .header p {
            font-size: 16px;
            opacity: 0.9;
        }

        .main-content-wrapper {
            display: flex;
            max-width: 1400px;
            margin: 0 auto;
            padding: 30px 20px;
            gap: 30px;
        }

        /* 左侧输入区域 */
        .shipping-calculator-input-section {
            flex: 1;
            background: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            height: fit-content;
        }

        .shipping-calculator-input-section h2 {
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 30px;
            color: #2c3e50;
        }

        .form-group {
            margin-bottom: 25px;
        }

        .form-group label {
            display: block;
            font-weight: 500;
            margin-bottom: 8px;
            color: #555;
        }

        .form-group input[type="text"],
        .form-group input[type="number"],
        .form-group select {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s ease;
        }

        .form-group input[type="text"]:focus,
        .form-group input[type="number"]:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }

        .form-group.origin-destination {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .form-group.origin-destination select {
            flex: 1;
        }

        .form-group.origin-destination .arrow {
            font-size: 20px;
            color: #667eea;
            font-weight: bold;
        }

        .form-group.weight-input {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .form-group.weight-input input {
            flex: 1;
        }

        .form-group.weight-input select {
            width: 80px;
        }

        .form-group.radio-group {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
        }

        .form-group.radio-group > div {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .form-group.radio-group input[type="radio"] {
            width: auto;
            margin: 0;
        }

        .form-group.package-size {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .form-group.package-size input {
            flex: 1;
        }

        .form-group.package-size select {
            width: 80px;
        }

        .form-group.two-column {
            display: flex;
            gap: 20px;
        }

        .form-group.two-column .column {
            flex: 1;
        }

        .form-group.two-column .column .form-group {
            margin-bottom: 0;
        }

        .action-buttons {
            display: flex;
            gap: 15px;
            margin-top: 30px;
        }

        .btn {
            padding: 14px 28px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            flex: 1;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
        }

        .btn-secondary {
            background: white;
            color: #667eea;
            border: 2px solid #667eea;
            flex: 1;
        }

        .btn-secondary:hover {
            background: #667eea;
            color: white;
        }

        /* 右侧结果区域 */
        .calculation-results-section {
            flex: 1;
            background: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }

        .calculation-results-section h2 {
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 15px;
            color: #2c3e50;
        }

        .disclaimer {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 25px;
            color: #856404;
            font-size: 14px;
        }

        .sort-options {
            display: flex;
            align-items: center;
            gap: 20px;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e1e5e9;
        }

        .sort-icon {
            font-size: 18px;
            color: #667eea;
        }

        .sort-item {
            padding: 8px 16px;
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
        }

        .sort-item.active {
            background: #667eea;
            color: white;
        }

        .sort-item:not(.active):hover {
            background: #f8f9fa;
        }

        .results-list {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .result-card {
            border: 2px solid #e1e5e9;
            border-radius: 12px;
            padding: 20px;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .result-card:hover {
            border-color: #667eea;
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
        }

        .card-header {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-bottom: 15px;
        }

        .tag {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
        }

        .tag.fastest-time {
            background: #e8f5e8;
            color: #27ae60;
        }

        .tag.best-price {
            background: #fff3cd;
            color: #f39c12;
        }

        .card-header h3 {
            font-size: 18px;
            font-weight: 600;
            color: #2c3e50;
        }

        .card-tags {
            display: flex;
            gap: 8px;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }

        .card-tags .tag {
            background: #f8f9fa;
            color: #6c757d;
            border: 1px solid #e9ecef;
        }

        .advantages {
            color: #6c757d;
            font-size: 14px;
            margin-bottom: 15px;
            line-height: 1.5;
        }

        .card-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .delivery-time {
            color: #667eea;
            font-weight: 500;
            font-size: 14px;
        }

        .price {
            font-size: 24px;
            font-weight: 700;
            color: #e74c3c;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .main-content-wrapper {
                flex-direction: column;
                padding: 20px 15px;
            }

            .form-group.origin-destination {
                flex-direction: column;
                gap: 10px;
            }

            .form-group.radio-group {
                flex-direction: column;
                gap: 10px;
            }

            .action-buttons {
                flex-direction: column;
            }

            .sort-options {
                flex-wrap: wrap;
                gap: 10px;
            }

            .form-group.two-column {
                flex-direction: column;
                gap: 15px;
            }
        }
    </style>

<div class="tms-container">
    <div class="shipping-calculator-page">

        <div class="main-content-wrapper">
            <!-- 左侧：运费计算器输入区域 -->
            <div class="shipping-calculator-input-section">
                <h2>Shipping Calculator</h2>

                <div class="form-group origin-destination">
                    <div style="flex: 1;">
                        <label for="shipping-origin">* Shipping Origin</label>
                        <select id="shipping-origin">
                            <option value="shanghai">Shanghai</option>
                            <option value="guangzhou">Guangzhou</option>
                            <option value="shenzhen">Shenzhen</option>
                            <option value="beijing">Beijing</option>
                        </select>
                    </div>
                    <div class="arrow">→</div>
                    <div style="flex: 1;">
                        <label for="destination">* Destination</label>
                        <select id="destination">
                            <option value="">Loading countries...</option>
                        </select>
                    </div>
                </div>

                <div class="form-group two-column">
                    <div class="column">
                        <div class="form-group weight-input">
                            <div style="flex: 1;">
                                <label for="package-weight">* Package Weight</label>
                                <input type="number" id="package-weight" value="2" step="0.1" min="0.1">
                            </div>
                            <div>
                                <label>&nbsp;</label>
                                <select>
                                    <option value="kg">KG</option>
                                    <option value="lbs">LBS</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="column">
                        <div class="form-group">
                            <label>Freight Type</label>
                            <div class="radio-group">
                                <div>
                                    <input type="radio" id="general-goods" name="freight-type" value="general" checked>
                                    <label for="general-goods">General Goods</label>
                                </div>
                                <div>
                                    <input type="radio" id="battery-containing" name="freight-type" value="battery">
                                    <label for="battery-containing">Battery-Containing</label>
                                </div>
                                <div>
                                    <input type="radio" id="specials" name="freight-type" value="specials">
                                    <label for="specials">Specials</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="form-group package-size">
                    <div style="flex: 1;">
                        <label>Package Size</label>
                        <div style="display: flex; gap: 10px;">
                            <input type="number" placeholder="L:" step="0.1" min="0.1">
                            <input type="number" placeholder="W:" step="0.1" min="0.1">
                            <input type="number" placeholder="H:" step="0.1" min="0.1">
                        </div>
                    </div>
                    <div>
                        <label>&nbsp;</label>
                        <select>
                            <option value="cm">CM</option>
                            <option value="inch">INCH</option>
                        </select>
                    </div>
                </div>

                <div class="form-group two-column">
                    <div class="column">
                        <div class="form-group">
                            <label for="destination-zip-code">Destination Zip Code</label>
                            <input type="text" id="destination-zip-code" placeholder="Enter destination zip code">
                        </div>
                    </div>
                    <div class="column">
                        <div class="form-group">
                            <label for="service-type">Service Type</label>
                            <select id="service-type">
                                <option value="">Select Service Type</option>
                                <option value="express">Express</option>
                                <option value="post">Standard</option>
                                <option value="economy">Economy</option>
                            </select>
                        </div>
                    </div>
                </div>


                <div class="action-buttons">
                    <button class="btn btn-primary" onclick="calculateShipping()">Cost Inquiry</button>
                    <button class="btn btn-primary" onclick="testYunExpressPricing()" style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%);">运费试算</button>
                    <button class="btn btn-primary" onclick="testYunExpressAuth()" style="background: linear-gradient(135deg, #dc3545 0%, #fd7e14 100%);">认证测试</button>
                    <button class="btn btn-primary" onclick="testOfficialExample()" style="background: linear-gradient(135deg, #6f42c1 0%, #e83e8c 100%);">官方示例测试</button>
                    <button class="btn btn-secondary" onclick="resetForm()">Reset</button>
                </div>
            </div>

            <!-- 右侧：计算结果展示区域 -->
            <div class="calculation-results-section">
                <h2>Calculation Results:</h2>

                <div class="results-list" id="results-list">
                    <!-- 结果卡片 1 -->
                    <div class="result-card">
                        <div class="card-header">
                            <span class="tag fastest-time">Fastest time</span>
                            <h3>HongKong DHL Express HKDHL</h3>
                        </div>
                        <div class="card-tags">
                            <span class="tag">Agent/International Express</span>
                            <span class="tag">Full tracking</span>
                            <span class="tag">Charged</span>
                        </div>
                        <p class="advantages">Advantages: Fast delivery, competitive price, worldwide coverage</p>
                        <div class="card-footer">
                            <span class="delivery-time">4-7 Working days</span>
                            <span class="price">¥190.44</span>
                        </div>
                    </div>

                    <!-- 结果卡片 2 -->
                    <div class="result-card">
                        <div class="card-header">
                            <span class="tag best-price">Best price</span>
                            <h3>Guangdong EUB EUB-SZ</h3>
                        </div>
                        <div class="card-tags">
                            <span class="tag">Agent/Postal Parcel</span>
                            <span class="tag">Full tracking</span>
                            <span class="tag">General cargo</span>
                        </div>
                        <p class="advantages">Advantages: High cost-performance, stable delivery time</p>
                        <div class="card-footer">
                            <span class="delivery-time">7-30 Working days</span>
                            <span class="price">¥146.02</span>
                        </div>
                    </div>

                    <!-- 结果卡片 3 -->
                    <div class="result-card">
                        <div class="card-header">
                            <h3>China Post Unregistered Air Mail-DongGuan CNDWA</h3>
                        </div>
                        <div class="card-tags">
                            <span class="tag">Agent/Postal Parcel</span>
                            <span class="tag">First-mile tracking</span>
                            <span class="tag">General cargo</span>
                        </div>
                        <p class="advantages">Advantages: Wide country coverage, affordable price, no remote area surcharge</p>
                        <div class="card-footer">
                            <span class="delivery-time">7-30 Working days</span>
                            <span class="price">¥179.22</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 表单验证
        function validateForm() {
            const origin = document.getElementById('shipping-origin').value;
            const destination = document.getElementById('destination').value;
            const weight = document.getElementById('package-weight').value;

            if (!origin || !destination || !weight) {
                alert('Please fill in all required fields (*)');
                return false;
            }

            if (parseFloat(weight) <= 0) {
                alert('Package weight must be greater than 0');
                return false;
            }

            return true;
        }

        // 计算运费
        function calculateShipping() {
            if (!validateForm()) {
                return;
            }

            // 显示加载状态
            const resultsList = document.getElementById('results-list');
            resultsList.innerHTML = '<div style="text-align: center; padding: 40px; color: #667eea;">Calculating shipping costs...</div>';

            // 收集表单数据
            const formData = collectFormData();
            
            // 打印输入参数到控制台
            console.log('=== 运费查询参数 ===');
            console.log('输入参数:', formData);
            console.log('参数详情:');
            console.log('  目的地国家:', formData.destination_country);
            console.log('  快运模式:', formData.shipping_mode);
            console.log('  走货属性:', formData.cargo_type);
            console.log('  长度(cm):', formData.length);
            console.log('  宽度(cm):', formData.width);
            console.log('  高度(cm):', formData.height);
            console.log('  重量(kg):', formData.weight);
            console.log('  目的地邮编:', formData.destination_postal_code);
            console.log('==================');
            
            // 调用真实的API
            callPricingAPI(formData);
        }

        // 云途官方示例测试
        function testOfficialExample() {
            // 显示加载状态
            const resultsList = document.getElementById('results-list');
            resultsList.innerHTML = '<div style="text-align: center; padding: 40px; color: #6f42c1;">正在使用云途API官方示例数据测试...</div>';
            
            console.log('=== 开始云途API官方示例数据测试 ===');
            
            // 调用官方示例测试API
            frappe.call({
                method: 'upsystem.upsystem.api.test_yunexpress_with_official_example',
                args: {},
                callback: function(response) {
                    console.log('=== 云途API官方示例测试响应 ===');
                    console.log('API响应:', response);
                    console.log('响应消息:', response.message);
                    
                    if (response.message && response.message.success) {
                        console.log('云途API官方示例测试成功');
                        displayOfficialExampleResults(response.message.data);
                    } else {
                        console.error('云途API官方示例测试失败:', response.message ? response.message.message : '测试失败');
                        displayError('云途API官方示例测试失败: ' + (response.message ? response.message.message : '测试失败'));
                    }
                },
                error: function(err) {
                    console.error('云途API官方示例测试API调用失败:', err);
                    displayError('网络错误，请稍后重试');
                }
            });
        }

        // 云途认证规则测试
        function testYunExpressAuth() {
            // 显示加载状态
            const resultsList = document.getElementById('results-list');
            resultsList.innerHTML = '<div style="text-align: center; padding: 40px; color: #dc3545;">正在测试云途API认证规则...</div>';
            
            console.log('=== 开始云途API认证规则测试 ===');
            
            // 调用认证规则测试API
            frappe.call({
                method: 'upsystem.upsystem.api.test_yunexpress_auth_rules',
                args: {},
                callback: function(response) {
                    console.log('=== 云途API认证规则测试响应 ===');
                    console.log('API响应:', response);
                    console.log('响应消息:', response.message);
                    
                    if (response.message && response.message.success) {
                        console.log('云途API认证规则测试成功');
                        displayAuthTestResults(response.message.data);
                    } else {
                        console.error('云途API认证规则测试失败:', response.message ? response.message.message : '测试失败');
                        displayError('云途API认证规则测试失败: ' + (response.message ? response.message.message : '测试失败'));
                    }
                },
                error: function(err) {
                    console.error('云途API认证规则测试API调用失败:', err);
                    displayError('网络错误，请稍后重试');
                }
            });
        }

        // 云途运费试算
        function testYunExpressPricing() {
            if (!validateForm()) {
                return;
            }

            // 显示加载状态
            const resultsList = document.getElementById('results-list');
            resultsList.innerHTML = '<div style="text-align: center; padding: 40px; color: #28a745;">正在测试云途运费计算...</div>';

            // 收集表单数据
            const formData = collectFormData();
            
            console.log('=== 云途运费试算参数 ===');
            console.log('输入参数:', formData);
            console.log('==================');
            
            // 调用云途运费试算API
            frappe.call({
                method: 'upsystem.upsystem.api.test_yunexpress_pricing',
                args: {
                    query_params: formData
                },
                callback: function(response) {
                    console.log('=== 云途运费试算API响应 ===');
                    console.log('API响应:', response);
                    console.log('响应消息:', response.message);
                    
                    if (response.message && response.message.success) {
                        console.log('云途运费试算成功');
                        displayYunExpressResults(response.message.data);
                    } else {
                        console.error('云途运费试算失败:', response.message ? response.message.message : '试算失败');
                        displayError('云途运费试算失败: ' + (response.message ? response.message.message : '试算失败'));
                    }
                },
                error: function(err) {
                    console.error('云途运费试算API调用失败:', err);
                    displayError('网络错误，请稍后重试');
                }
            });
        }

        // 收集表单数据
        function collectFormData() {
            const origin = document.getElementById('shipping-origin').value;
            const destination = document.getElementById('destination').value;
            const weight = parseFloat(document.getElementById('package-weight').value);
            const weightUnit = document.querySelector('select').value;
            
            // 获取尺寸数据
            const sizeInputs = document.querySelectorAll('.package-size input[type="number"]');
            const length = parseFloat(sizeInputs[0].value) || 0;
            const width = parseFloat(sizeInputs[1].value) || 0;
            const height = parseFloat(sizeInputs[2].value) || 0;
            const sizeUnit = document.querySelector('.package-size select').value;
            
            // 获取其他参数
            const zipCode = document.getElementById('destination-zip-code').value;
            const serviceType = document.getElementById('service-type').value;
            const freightType = document.querySelector('input[name="freight-type"]:checked').value;
            
            // 转换重量单位到kg
            let weightInKg = weight;
            if (weightUnit === 'lbs') {
                weightInKg = weight * 0.453592;
            }
            
            // 转换尺寸单位到cm
            let lengthInCm = length;
            let widthInCm = width;
            let heightInCm = height;
            if (sizeUnit === 'inch') {
                lengthInCm = length * 2.54;
                widthInCm = width * 2.54;
                heightInCm = height * 2.54;
            }
            
            return {
                destination_country: destination,
                shipping_mode: serviceType,
                cargo_type: freightType,
                length: lengthInCm,
                width: widthInCm,
                height: heightInCm,
                weight: weightInKg,
                destination_postal_code: zipCode
            };
        }

        // 调用定价API
        function callPricingAPI(formData) {
            console.log('开始调用API: upsystem.upsystem.api.get_pricing_quote');
            console.log('API参数:', formData);
            
            frappe.call({
                method: 'upsystem.upsystem.api.get_pricing_quote',
                args: {
                    query_params: formData
                },
                callback: function(response) {
                    console.log('=== API完整响应 ===');
                    console.log('API响应:', response);
                    console.log('响应消息:', response.message);
                    
                    if (response.message && response.message.success) {
                        console.log('API调用成功，开始显示结果');
                        console.log('=== 返回数据结构分析 ===');
                        console.log('完整返回数据:', response.message.data);
                        console.log('data.products:', response.message.data.products);
                        console.log('data.available_products:', response.message.data.available_products);
                        console.log('data.pricing_data:', response.message.data.pricing_data);
                        console.log('data.summary:', response.message.data.summary);
                        
                        // 详细分析每个数据结构
                        if (response.message.data.products) {
                            console.log('=== products 详细分析 ===');
                            Object.keys(response.message.data.products).forEach(key => {
                                console.log(`products[${key}]:`, response.message.data.products[key]);
                            });
                        }
                        
                        if (response.message.data.available_products) {
                            console.log('=== available_products 详细分析 ===');
                            Object.keys(response.message.data.available_products).forEach(key => {
                                console.log(`available_products[${key}]:`, response.message.data.available_products[key]);
                            });
                        }
                        
                        if (response.message.data.pricing_data) {
                            console.log('=== pricing_data 详细分析 ===');
                            Object.keys(response.message.data.pricing_data).forEach(country => {
                                console.log(`pricing_data[${country}]:`, response.message.data.pricing_data[country]);
                                if (response.message.data.pricing_data[country]) {
                                    Object.keys(response.message.data.pricing_data[country]).forEach(product => {
                                        console.log(`  pricing_data[${country}][${product}]:`, response.message.data.pricing_data[country][product]);
                                    });
                                }
                            });
                        }
                        
                        console.log('=== 开始显示结果 ===');
                        displayResults(response.message.data);
                    } else {
                        console.error('API调用失败:', response.message ? response.message.message : '查询失败');
                        displayError(response.message ? response.message.message : '查询失败');
                    }
                },
                error: function(err) {
                    console.error('API调用失败:', err);
                    console.error('错误详情:', err);
                    displayError('网络错误，请稍后重试');
                }
            });
        }

        // 显示云途官方示例测试结果
        function displayOfficialExampleResults(data) {
            const resultsList = document.getElementById('results-list');
            
            console.log('=== displayOfficialExampleResults 开始处理 ===');
            console.log('云途官方示例测试结果:', data);
            
            if (!data) {
                resultsList.innerHTML = '<div style="text-align: center; padding: 40px; color: #e74c3c;">未获取到云途官方示例测试结果</div>';
                return;
            }
            
            let html = '<div style="background: #f3e5f5; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
            html += '<h3 style="color: #6f42c1; margin: 0 0 10px 0;">云途API官方示例数据测试结果</h3>';
            html += '</div>';
            
            // 显示请求数据
            html += '<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
            html += '<h4>官方示例请求数据:</h4>';
            html += '<pre style="background: white; padding: 10px; border-radius: 4px; overflow-x: auto; font-size: 12px;">';
            html += JSON.stringify(data.request_data, null, 2);
            html += '</pre>';
            html += '</div>';
            
            // 显示API响应
            html += '<div style="background: #e8f5e8; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
            html += '<h4>云途API响应:</h4>';
            html += '<pre style="background: white; padding: 10px; border-radius: 4px; overflow-x: auto; font-size: 12px;">';
            html += JSON.stringify(data.response, null, 2);
            html += '</pre>';
            html += '</div>';
            
            // 显示测试时间
            html += '<div style="background: #fff3cd; padding: 15px; border-radius: 8px;">';
            html += '<h4>测试信息:</h4>';
            html += `<p><strong>测试时间:</strong> ${data.test_timestamp}</p>`;
            html += '<p><strong>说明:</strong> 此测试使用了云途API官方文档中的完整示例数据，用于验证API接口是否正常工作。</p>';
            html += '</div>';
            
            resultsList.innerHTML = html;
        }

        // 显示云途认证测试结果
        function displayAuthTestResults(data) {
            const resultsList = document.getElementById('results-list');
            
            console.log('=== displayAuthTestResults 开始处理 ===');
            console.log('云途认证测试结果:', data);
            
            if (!data) {
                resultsList.innerHTML = '<div style="text-align: center; padding: 40px; color: #e74c3c;">未获取到云途认证测试结果</div>';
                return;
            }
            
            let html = '<div style="background: #f8d7da; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
            html += '<h3 style="color: #dc3545; margin: 0 0 10px 0;">云途API认证规则测试结果</h3>';
            html += '</div>';
            
            // 显示各项测试结果
            html += '<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
            html += '<h4>测试项目结果:</h4>';
            
            const tests = [
                { name: 'Token获取测试', result: data.token_test, color: data.token_test === '成功' ? '#28a745' : '#dc3545' },
                { name: '签名计算测试', result: data.signature_test, color: data.signature_test === '成功' ? '#28a745' : '#dc3545' },
                { name: '请求头格式测试', result: data.headers_test, color: data.headers_test === '成功' ? '#28a745' : '#dc3545' },
                { name: 'API配置测试', result: data.config_test, color: data.config_test === '成功' ? '#28a745' : '#dc3545' },
                { name: 'API调用测试', result: data.api_call_test, color: data.api_call_test === '成功' ? '#28a745' : '#dc3545' }
            ];
            
            tests.forEach(test => {
                html += `<div style="margin: 10px 0; padding: 10px; background: white; border-radius: 4px; border-left: 4px solid ${test.color};">`;
                html += `<strong>${test.name}:</strong> <span style="color: ${test.color};">${test.result}</span>`;
                html += `</div>`;
            });
            
            html += '</div>';
            
            // 添加401错误分析
            html += '<div style="background: #fff3cd; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
            html += '<h4>401错误可能原因分析:</h4>';
            html += '<ul style="margin: 10px 0; padding-left: 20px;">';
            html += '<li><strong>0200401001</strong> - 缺少访问令牌 (Missing access token)</li>';
            html += '<li><strong>0200401002</strong> - 访问令牌无效或已过期 (Access token invalid or expired)</li>';
            html += '<li><strong>0200401101</strong> - 缺少访问签名 (Missing access signature)</li>';
            html += '<li><strong>0200401102</strong> - 访问签名无效或已过期 (Access signature invalid or expired)</li>';
            html += '</ul>';
            html += '</div>';
            
            // 添加建议
            html += '<div style="background: #d1ecf1; padding: 15px; border-radius: 8px;">';
            html += '<h4>建议检查项目:</h4>';
            html += '<ol style="margin: 10px 0; padding-left: 20px;">';
            html += '<li>检查 appKey、appSecret、sourceKey 配置是否正确</li>';
            html += '<li>检查签名计算算法是否符合云途API要求</li>';
            html += '<li>检查请求头格式是否正确</li>';
            html += '<li>检查时间戳格式是否正确</li>';
            html += '<li>检查API接口地址是否正确</li>';
            html += '</ol>';
            html += '</div>';
            
            resultsList.innerHTML = html;
        }

        // 显示云途运费试算结果
        function displayYunExpressResults(data) {
            const resultsList = document.getElementById('results-list');
            
            console.log('=== displayYunExpressResults 开始处理 ===');
            console.log('云途运费试算结果:', data);
            
            if (!data) {
                resultsList.innerHTML = '<div style="text-align: center; padding: 40px; color: #e74c3c;">未获取到云途运费试算结果</div>';
                return;
            }
            
            let html = '<div style="background: #e8f5e8; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
            html += '<h3 style="color: #28a745; margin: 0 0 10px 0;">云途运费试算结果</h3>';
            html += '</div>';
            
            // 显示原始响应数据
            html += '<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
            html += '<h4>API响应详情:</h4>';
            html += '<pre style="background: white; padding: 10px; border-radius: 4px; overflow-x: auto; font-size: 12px;">';
            html += JSON.stringify(data, null, 2);
            html += '</pre>';
            html += '</div>';
            
            // 如果有具体的运费信息，显示格式化结果
            if (data.products && Object.keys(data.products).length > 0) {
                html += '<div style="background: #fff3cd; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
                html += '<h4>可用产品:</h4>';
                Object.entries(data.products).forEach(([productName, product]) => {
                    html += `<div style="margin: 10px 0; padding: 10px; background: white; border-radius: 4px;">`;
                    html += `<strong>${productName}</strong><br>`;
                    if (product.description) {
                        html += `描述: ${product.description}<br>`;
                    }
                    if (product.available_countries) {
                        html += `支持国家: ${product.available_countries.join(', ')}<br>`;
                    }
                    html += `</div>`;
                });
                html += '</div>';
            }
            
            resultsList.innerHTML = html;
        }

        // 显示结果
        function displayResults(data) {
            const resultsList = document.getElementById('results-list');
            
            console.log('=== displayResults 开始处理 ===');
            console.log('displayResults 接收到的数据:', data);
            
            // 检查数据是否存在
            if (!data) {
                console.log('数据为空，显示错误');
                resultsList.innerHTML = '<div>未找到可用的物流线路</div>';
                return;
            }
            
            // 收集所有产品及其计费信息
            let productsData = {};
            
            // 从 available_products 中提取数据
            if (data.available_products) {
                Object.entries(data.available_products).forEach(([productName, records]) => {
                    if (Array.isArray(records)) {
                        productsData[productName] = records;
                    }
                });
            }
            
            // 从 products 中提取数据
            if (data.products) {
                Object.entries(data.products).forEach(([productName, product]) => {
                    if (product.pricing_records && Array.isArray(product.pricing_records)) {
                        productsData[productName] = product.pricing_records;
                    }
                });
            }
            
            // 从 pricing_data 中提取数据
            if (data.pricing_data) {
                Object.values(data.pricing_data).forEach(countryData => {
                    if (countryData) {
                        Object.entries(countryData).forEach(([productName, records]) => {
                            if (Array.isArray(records)) {
                                if (!productsData[productName]) {
                                    productsData[productName] = [];
                                }
                                productsData[productName] = productsData[productName].concat(records);
                            }
                        });
                    }
                });
            }
            
            console.log('按产品分组的数据:', productsData);
            
            // 初始化HTML变量
            let html = '';
            
            // 为每个产品创建分组表格
            Object.entries(productsData).forEach(([productName, records]) => {
                if (records.length === 0) return;
                
                html += `<div style="margin-bottom: 20px;">`;
                html += `<h3 style="background-color: #e8f4f8; padding: 10px; margin: 0; border: 1px solid #ccc;">${productName}</h3>`;
                html += '<table border="1" cellpadding="5" cellspacing="0" style="width: 100%; border-collapse: collapse;">';
                html += '<thead style="background-color: #f0f8f0;">';
                html += '<tr>';
                html += '<th>国家/地区</th>';
                html += '<th>参考时效</th>';
                html += '<th>分区</th>';
                html += '<th>重量(KG)</th>';
                html += '<th>进位制(KG)</th>';
                html += '<th>最低计费重(KG)</th>';
                html += '<th>运费(RMB/KG)</th>';
                html += '<th>挂号费(RMB/票)</th>';
                html += '</tr>';
                html += '</thead>';
                html += '<tbody>';
                
                // 为每个记录创建一行
                records.forEach((record, index) => {
                    const rowClass = index % 2 === 0 ? 'style="background-color: #f9f9f9;"' : 'style="background-color: white;"';
                    html += `<tr ${rowClass}>`;
                    html += `<td>${record.country || ''}</td>`;
                    html += `<td>${record.timeliness || ''}</td>`;
                    html += `<td>${record.zone || ''}</td>`;
                    html += `<td>${record.weight || ''}</td>`;
                    html += `<td>${record.increment || ''}</td>`;
                    html += `<td>${record.min_weight || ''}</td>`;
                    html += `<td>${record.freight || ''}</td>`;
                    html += `<td>${record.registration || ''}</td>`;
                    html += '</tr>';
                });
                
                html += '</tbody>';
                html += '</table>';
                html += '</div>';
            });
            
            if (Object.keys(productsData).length === 0) {
                html = '<div>未找到可用的物流线路数据</div>';
            }
            
            resultsList.innerHTML = html;
        }

        // 显示错误信息
        function displayError(message) {
            const resultsList = document.getElementById('results-list');
            resultsList.innerHTML = `<div style="text-align: center; padding: 40px; color: #e74c3c;">${message}</div>`;
        }

        // 重置表单
        function resetForm() {
            document.getElementById('shipping-origin').value = 'shanghai';
            document.getElementById('destination').value = '';
            document.getElementById('package-weight').value = '2';
            document.getElementById('destination-zip-code').value = '';
            document.getElementById('service-type').value = '';
            
            // 重置尺寸输入
            const sizeInputs = document.querySelectorAll('.package-size input[type="number"]');
            sizeInputs.forEach(input => input.value = '');
            
            // 重置单选按钮
            document.getElementById('general-goods').checked = true;
            document.getElementById('not-required-pod').checked = true;
            
            // 清空结果
            document.getElementById('results-list').innerHTML = '';
        }

        // 排序结果
        function sortResults(type) {
            const sortItems = document.querySelectorAll('.sort-item');
            sortItems.forEach(item => item.classList.remove('active'));
            
            if (type === 'timeliness') {
                sortItems[0].classList.add('active');
                // 按时效排序逻辑
            } else if (type === 'cost') {
                sortItems[1].classList.add('active');
                // 按价格排序逻辑
            }
        }

        // 加载国家列表
        function loadCountries() {
            console.log('开始加载国家列表...');
            frappe.call({
                method: 'upsystem.upsystem.api.get_country_codes',
                callback: function(response) {
                    console.log('API响应:', response);
                    console.log('响应消息:', response.message);
                    
                    if (response.message && response.message.success) {
                        console.log('成功获取国家数据');
                        const countries_data = response.message.data || [];
                        console.log('原始国家数据:', countries_data);
                        
                        // 从云途API返回的数据中提取国家名称
                        const countries = countries_data.map(country => country.country_name || country.name || country).filter(name => name);
                        console.log('国家列表:', countries);
                        console.log('国家数量:', countries.length);
                        
                        const destinationSelect = document.getElementById('destination');
                        
                        destinationSelect.innerHTML = '<option value="">Select Destination</option>';
                        countries.forEach(country => {
                            const option = document.createElement('option');
                            option.value = country;
                            option.textContent = country;
                            destinationSelect.appendChild(option);
                        });
                    } else {
                        console.error('获取国家列表失败:', response.message ? response.message.message : '未知错误');
                        console.error('完整响应:', response);
                        // 如果加载失败，使用默认国家列表
                        loadDefaultCountries();
                    }
                },
                error: function(err) {
                    console.error('API调用失败:', err);
                    console.error('错误详情:', err);
                    loadDefaultCountries();
                }
            });
        }

        // 加载默认国家列表
        function loadDefaultCountries() {
            const destinationSelect = document.getElementById('destination');
            const defaultCountries = [
                '德国', '美国', '英国', '法国', '加拿大', '澳大利亚', 
                '日本', '韩国', '新加坡', '马来西亚', '泰国', '印度尼西亚'
            ];
            
            destinationSelect.innerHTML = '<option value="">Select Destination</option>';
            defaultCountries.forEach(country => {
                const option = document.createElement('option');
                option.value = country;
                option.textContent = country;
                destinationSelect.appendChild(option);
            });
        }

        // 云途官方示例测试
        function testOfficialExample() {
            // 显示加载状态
            const resultsList = document.getElementById('results-list');
            resultsList.innerHTML = '<div style="text-align: center; padding: 40px; color: #6f42c1;">正在使用云途API官方示例数据测试...</div>';
            
            console.log('=== 开始云途API官方示例数据测试 ===');
            
            // 调用官方示例测试API
            frappe.call({
                method: 'upsystem.upsystem.api.test_yunexpress_with_official_example',
                args: {},
                callback: function(response) {
                    console.log('=== 云途API官方示例测试响应 ===');
                    console.log('API响应:', response);
                    console.log('响应消息:', response.message);
                    
                    if (response.message && response.message.success) {
                        console.log('云途API官方示例测试成功');
                        displayOfficialExampleResults(response.message.data);
                    } else {
                        console.error('云途API官方示例测试失败:', response.message ? response.message.message : '测试失败');
                        displayError('云途API官方示例测试失败: ' + (response.message ? response.message.message : '测试失败'));
                    }
                },
                error: function(err) {
                    console.error('云途API官方示例测试API调用失败:', err);
                    displayError('网络错误，请稍后重试');
                }
            });
        }

        // 云途认证规则测试
        function testYunExpressAuth() {
            // 显示加载状态
            const resultsList = document.getElementById('results-list');
            resultsList.innerHTML = '<div style="text-align: center; padding: 40px; color: #dc3545;">正在测试云途API认证规则...</div>';
            
            console.log('=== 开始云途API认证规则测试 ===');
            
            // 调用认证规则测试API
            frappe.call({
                method: 'upsystem.upsystem.api.test_yunexpress_auth_rules',
                args: {},
                callback: function(response) {
                    console.log('=== 云途API认证规则测试响应 ===');
                    console.log('API响应:', response);
                    console.log('响应消息:', response.message);
                    
                    if (response.message && response.message.success) {
                        console.log('云途API认证规则测试成功');
                        displayAuthTestResults(response.message.data);
                    } else {
                        console.error('云途API认证规则测试失败:', response.message ? response.message.message : '测试失败');
                        displayError('云途API认证规则测试失败: ' + (response.message ? response.message.message : '测试失败'));
                    }
                },
                error: function(err) {
                    console.error('云途API认证规则测试API调用失败:', err);
                    displayError('网络错误，请稍后重试');
                }
            });
        }

        // 云途运费试算
        function testYunExpressPricing() {
            if (!validateForm()) {
                return;
            }

            // 显示加载状态
            const resultsList = document.getElementById('results-list');
            resultsList.innerHTML = '<div style="text-align: center; padding: 40px; color: #28a745;">正在测试云途运费计算...</div>';
            const formData = collectFormData();
            console.log('=== 云途运费试算参数 ===');
            console.log('输入参数:', formData);
            console.log('==================');
            frappe.call({
                method: 'upsystem.upsystem.api.test_yunexpress_pricing',
                args: {
                    query_params: formData
                },
                callback: function(response) {
                    console.log('=== 云途运费试算API响应 ===');
                    console.log('API响应:', response);
                    console.log('响应消息:', response.message);
                    if (response.message && response.message.success) {
                        console.log('云途运费试算成功');
                        displayYunExpressResults(response.message.data);
                    } else {
                        console.error('云途运费试算失败:', response.message ? response.message.message : '试算失败');
                        displayError('云途运费试算失败: ' + (response.message ? response.message.message : '试算失败'));
                    }
                },
                error: function(err) {
                    console.error('云途运费试算API调用失败:', err);
                    displayError('网络错误，请稍后重试');
                }
            });
        }

        // 显示云途官方示例测试结果
        function displayOfficialExampleResults(data) {
            const resultsList = document.getElementById('results-list');
            
            console.log('=== displayOfficialExampleResults 开始处理 ===');
            console.log('云途官方示例测试结果:', data);
            
            if (!data) {
                resultsList.innerHTML = '<div style="text-align: center; padding: 40px; color: #e74c3c;">未获取到云途官方示例测试结果</div>';
                return;
            }
            
            let html = '<div style="background: #f3e5f5; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
            html += '<h3 style="color: #6f42c1; margin: 0 0 10px 0;">云途API官方示例数据测试结果</h3>';
            html += '</div>';
            
            // 显示请求数据
            html += '<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
            html += '<h4>官方示例请求数据:</h4>';
            html += '<pre style="background: white; padding: 10px; border-radius: 4px; overflow-x: auto; font-size: 12px;">';
            html += JSON.stringify(data.request_data, null, 2);
            html += '</pre>';
            html += '</div>';
            
            // 显示API响应
            html += '<div style="background: #e8f5e8; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
            html += '<h4>云途API响应:</h4>';
            html += '<pre style="background: white; padding: 10px; border-radius: 4px; overflow-x: auto; font-size: 12px;">';
            html += JSON.stringify(data.response, null, 2);
            html += '</pre>';
            html += '</div>';
            
            // 显示测试时间
            html += '<div style="background: #fff3cd; padding: 15px; border-radius: 8px;">';
            html += '<h4>测试信息:</h4>';
            html += `<p><strong>测试时间:</strong> ${data.test_timestamp}</p>`;
            html += '<p><strong>说明:</strong> 此测试使用了云途API官方文档中的完整示例数据，用于验证API接口是否正常工作。</p>';
            html += '</div>';
            
            resultsList.innerHTML = html;
        }

        // 显示云途认证测试结果
        function displayAuthTestResults(data) {
            const resultsList = document.getElementById('results-list');
            
            console.log('=== displayAuthTestResults 开始处理 ===');
            console.log('云途认证测试结果:', data);
            
            if (!data) {
                resultsList.innerHTML = '<div style="text-align: center; padding: 40px; color: #e74c3c;">未获取到云途认证测试结果</div>';
                return;
            }
            
            let html = '<div style="background: #f8d7da; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
            html += '<h3 style="color: #dc3545; margin: 0 0 10px 0;">云途API认证规则测试结果</h3>';
            html += '</div>';
            
            // 显示各项测试结果
            html += '<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
            html += '<h4>测试项目结果:</h4>';
            
            const tests = [
                { name: 'Token获取测试', result: data.token_test, color: data.token_test === '成功' ? '#28a745' : '#dc3545' },
                { name: '签名计算测试', result: data.signature_test, color: data.signature_test === '成功' ? '#28a745' : '#dc3545' },
                { name: '请求头格式测试', result: data.headers_test, color: data.headers_test === '成功' ? '#28a745' : '#dc3545' },
                { name: 'API配置测试', result: data.config_test, color: data.config_test === '成功' ? '#28a745' : '#dc3545' },
                { name: 'API调用测试', result: data.api_call_test, color: data.api_call_test === '成功' ? '#28a745' : '#dc3545' }
            ];
            
            tests.forEach(test => {
                html += `<div style="margin: 10px 0; padding: 10px; background: white; border-radius: 4px; border-left: 4px solid ${test.color};">`;
                html += `<strong>${test.name}:</strong> <span style="color: ${test.color};">${test.result}</span>`;
                html += `</div>`;
            });
            
            html += '</div>';
            
            // 添加401错误分析
            html += '<div style="background: #fff3cd; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
            html += '<h4>401错误可能原因分析:</h4>';
            html += '<ul style="margin: 10px 0; padding-left: 20px;">';
            html += '<li><strong>0200401001</strong> - 缺少访问令牌 (Missing access token)</li>';
            html += '<li><strong>0200401002</strong> - 访问令牌无效或已过期 (Access token invalid or expired)</li>';
            html += '<li><strong>0200401101</strong> - 缺少访问签名 (Missing access signature)</li>';
            html += '<li><strong>0200401102</strong> - 访问签名无效或已过期 (Access signature invalid or expired)</li>';
            html += '</ul>';
            html += '</div>';
            
            // 添加建议
            html += '<div style="background: #d1ecf1; padding: 15px; border-radius: 8px;">';
            html += '<h4>建议检查项目:</h4>';
            html += '<ol style="margin: 10px 0; padding-left: 20px;">';
            html += '<li>检查 appKey、appSecret、sourceKey 配置是否正确</li>';
            html += '<li>检查签名计算算法是否符合云途API要求</li>';
            html += '<li>检查请求头格式是否正确</li>';
            html += '<li>检查时间戳格式是否正确</li>';
            html += '<li>检查API接口地址是否正确</li>';
            html += '</ol>';
            html += '</div>';
            
            resultsList.innerHTML = html;
        }

        // 显示云途运费试算结果
        function displayYunExpressResults(data) {
            const resultsList = document.getElementById('results-list');
            
            console.log('=== displayYunExpressResults 开始处理 ===');
            console.log('云途运费试算结果:', data);
            
            if (!data) {
                resultsList.innerHTML = '<div style="text-align: center; padding: 40px; color: #e74c3c;">未获取到云途运费试算结果</div>';
                return;
            }
            
            let html = '<div style="background: #e8f5e8; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
            html += '<h3 style="color: #28a745; margin: 0 0 10px 0;">云途运费试算结果</h3>';
            html += '</div>';
            
            // 显示API响应详情
            html += '<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
            html += '<h4>API响应详情:</h4>';
            html += '<pre style="background: white; padding: 10px; border-radius: 4px; overflow-x: auto; font-size: 12px;">';
            html += JSON.stringify(data, null, 2);
            html += '</pre>';
            html += '</div>';
            
            if (data.products && Object.keys(data.products).length > 0) {
                html += '<div style="background: #fff3cd; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
                html += '<h4>可用产品:</h4>';
                Object.entries(data.products).forEach(([productName, product]) => {
                    html += `<div style="margin: 10px 0; padding: 10px; background: white; border-radius: 4px;">`;
                    html += `<strong>${productName}</strong><br>`;
                    if (product.description) {
                        html += `描述: ${product.description}<br>`;
                    }
                    if (product.available_countries) {
                        html += `支持国家: ${product.available_countries.join(', ')}<br>`;
                    }
                    html += `</div>`;
                });
                html += '</div>';
            }
            
            resultsList.innerHTML = html;
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('Shipping Calculator loaded');
            loadCountries();
        });
    </script>

<script src="/assets/upsystem/js/tms_common.js"></script>
</div>
{% endblock %}
